import React, { Component } from 'react'
import { Button, Space, Spin, Tooltip, message } from 'antd';
import { FolderOutlined, FileExcelOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';

import MyTree from 'src/component/MyTree'
import PlanDialog from './PlanDialog'
import PlanExecDialog from './PlanExecDialog'
import { MyModal } from 'src/util/utils'

import SparkChannel, { EE } from 'src/ipc/sparkchannel'

function buildTreeData(planList) {
  const map = planList.reduce((pre, cur) => {
    const picker_type = cur.picker_type;
    const arr = pre[picker_type];
    if (arr) {
      const node = {
        title: cur.name,
        key: cur.id,
        icon: <FileExcelOutlined />,
        data: cur,
      };
      arr.push(node);
    }
    return pre;
  }, { DATE: [], RANGE: [], COMPRANGE: [] });

  const treeData = [
    {
      title: '单日',
      key: 'DATE',
      icon: <FolderOutlined />,
      children: map['DATE'],
    },
    {
      title: '多日',
      key: 'RANGE',
      icon: <FolderOutlined />,
      children: map['RANGE'],
    },
    {
      title: '多日对照',
      key: 'COMPRANGE',
      icon: <FolderOutlined />,
      children: map['COMPRANGE'],
    },
  ];
  return treeData;
}

class QueryPlanPanel extends Component {
  constructor(props) {
    super(props);

    this.reloadPlanTree = this.reloadPlanTree.bind(this);
    this.onExpand = this.onExpand.bind(this);
    this.onSelect = this.onSelect.bind(this);
    this.onDoubleClick = this.onDoubleClick.bind(this);
    this.deletePlan = this.deletePlan.bind(this);
    this.editPlan = this.editPlan.bind(this);
    this.hidePlanDialog = this.hidePlanDialog.bind(this);
    this.updateQueryPlan = this.updateQueryPlan.bind(this);
    this.hidePlanExecDialog = this.hidePlanExecDialog.bind(this);
    this.execQueryPlan = this.execQueryPlan.bind(this);

    this.state = {
      loading: true,
      treeData: [],
      expandedKeys: [],
      selectedNode: null,
      planDialogOpen: false,
      plan: null,
      planExecDialogOpen: false,
    };
  }

  componentDidMount() {
    this.reloadPlanTree();

    EE.on('plan-list-changed', this.reloadPlanTree);
  }

  componentWillUnmount() {
    EE.removeListener('plan-list-changed', this.reloadPlanTree);
  }

  reloadPlanTree() {
    this.setState({ loading: true });

    SparkChannel().then(channel => {
      return channel.request_get_curve_plan_list();
    }).then(resp => {
      // console.log('Got tree data', resp);
      const planList = resp.data.curve_plan_list;
      const treeData = buildTreeData(planList);

      this.setState({
        loading: false,
        treeData: treeData
      });
    }).catch((err) => {
      console.log('Got tree fail', err);
      this.setState({ loading: false });
      message.error('加载目录树失败');
    });
  }

  onExpand(expandedKeysValue) {
    this.setState({ expandedKeys: expandedKeysValue })
  }
  onSelect(selectedKeysValue, info) {
    // console.log('onSelect', selectedKeysValue, info);
    const node = info.node;
    this.setState({ selectedNode: node });
  }
  onDoubleClick(node) {
    if (node.data) {
      const plan = node.data;

      this.setState({
        plan,
        planExecDialogOpen: true,
      });
    } else {
      // 切换展开状态
      this.setState((state) => {
        const expandedKeys = state.expandedKeys;
        const index = expandedKeys.indexOf(node.key);
        let result;
        if (index === -1) {
          result = expandedKeys.concat(node.key);
        } else {
          result = expandedKeys.filter(k => k !== node.key);
        }
        return { expandedKeys: result };
      });
    }
  }

  deletePlan() {
    const self = this;
    const node = this.state.selectedNode;
    const plan = node && node.data;
    if (!plan) {
      MyModal.warning({ content: '请选择查询计划' });
    } else {
      MyModal.confirm({
        content: `确定删除“${plan.name}”`,
        async onOk() {
          try {
            const channel = await SparkChannel();
            const resp = await channel.request_delete_curve_plan({ id: plan.id });
            console.log('delete curve plan success', resp);

            self.reloadPlanTree();
          } catch (err) {
            console.log('Delete plan fail', err);
            message.error('删除失败');
          }
        },
      });
    }
  }
  editPlan() {
    const node = this.state.selectedNode;
    const plan = node && node.data;
    if (!plan) {
      MyModal.warning({ content: '请选择查询计划' });
    } else {
      console.log('tttt', plan)
      this.setState({
        planDialogOpen: true,
        plan: plan,
      });
    }
  }
  hidePlanDialog() {
    this.setState({ planDialogOpen: false });
  }
  async updateQueryPlan(plan) {
    const channel = await SparkChannel();
    const resp = await channel.request_update_curve_plan({
      id: plan.id,
      name: plan.name,
      picker_type: plan.picker_type,
      mode_type: plan.mode_type,
      data_interval: plan.data_interval,
      interval_unit: plan.interval_unit,
      point_list: plan.point_list,
    });
    console.log('update curve plan success', resp);

    this.hidePlanDialog();

    this.reloadPlanTree();
  }

  hidePlanExecDialog() {
    this.setState({ planExecDialogOpen: false });
  }
  execQueryPlan(plan) {
    this.setState({ planExecDialogOpen: false });
    EE.emit('open-curve', plan);
  }

  render() {
    const state = this.state;
    const node = this.state.selectedNode;
    const selectedKeys = node ? [node.key] : [];

    return (
      <div className='query-plan-panel'>
        <div className='tree-toolbar'>
          <Space>
            <Tooltip title="删除计划">
              <Button icon={<DeleteOutlined />} onClick={this.deletePlan} />
            </Tooltip>
            <Tooltip title="编辑">
              <Button icon={<EditOutlined />} onClick={this.editPlan} />
            </Tooltip>
          </Space>
        </div>

        <Spin spinning={state.loading}>
          <MyTree
            showIcon
            defaultExpandAll
            expandedKeys={state.expandedKeys}
            selectedKeys={selectedKeys}
            treeData={state.treeData}
            onExpand={this.onExpand}
            onSelect={this.onSelect}
            onDoubleClick={this.onDoubleClick}
          />
        </Spin>

        {state.planDialogOpen &&
          <PlanDialog
            edit
            open={state.planDialogOpen}
            plan={state.plan}
            onCancel={this.hidePlanDialog}
            onSubmit={this.updateQueryPlan} />}
        {state.planExecDialogOpen &&
          <PlanExecDialog
            open={state.planExecDialogOpen}
            plan={state.plan}
            onCancel={this.hidePlanExecDialog}
            onSubmit={this.execQueryPlan} />}

      </div>
    );
  }
}

export default QueryPlanPanel